#!/usr/bin/ruby
#

require 'nkf'
require 'uri'
require 'mysql'
require 'rexml/document'
require 'net/http'
require 'date'

require 'aws'
require '../db_setting'

db = Mysql::new(DB_HOST, DB_USER, DB_PASS, DB_NAME)
res = db.query("select asin from books where year(publication_date) = 0")
res.each do |row|
  asin = row[0]
  Net::HTTP.start(AWS_URL, 80) do |http|
    request =
      AWS_PATH + '?' +
      'Service=AWSECommerceService&' +
      "AWSAccessKeyId=#{AWS_ACCESS_KEY_ID}&" +
      "Version=#{AWS_VERSION}&" +
      "Operation=ItemLookup&" +
      "ItemId=#{asin}&" +
      "ResponseGroup=ItemAttributes"
    res = http.get(request)  
    puts res.body
    doc = REXML::Document.new(res.body)
    pub_date = doc.elements["//PublicationDate"].text
    
    if pub_date.count('-') == 1 then
      pub_date += "-1"
    end

    sql = "update books set publication_date = '#{pub_date}' where asin = '#{asin}'"
    puts sql
    db.query(sql)
  end
end

